//中间件的使用
'use strict'
const titbit = require('titbit');
const { cookie, session } = require('titbit-toolkit')

const app = new titbit({
    debug: true//如果出错报出错误信息
})

app.use((new cookie()).mid())
app.use((new session()).mid())
//全部都是分组执行的，每一个中间件之间并不相互影响
app.use(async(c,next)=>{
    console.log('just for home');
    await next()
},{group:'home'})


app.get('/', async c => {
    c.res.body = 'hello wangyibo'

},{name:'首页',group:'home'})



app.get('/login', async c => {
    c.res.body = `<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
    <form action="/login" method="post">
    <input type="text" name="username">
    <input type="password" name="passwd">
    <input type="submit" value="login">

    </form>
        
    </body>
    </html>`
})

app.post('/login',async c=>{

    let {username,passwd}=c.body
    if(username==='testuser' && passwd==='1234560'){
        c.setSession('is_login',true)
        c.status(301)
        c.setHeader('Location','/')
    }else{
        c.status(301)
        c.setHeader('location','/login')
    }
    //提交数据解析到c.body
    console.log(c.body);
    c.res.body=c.body;
})

app.get('/cookie', async c => {
    c.res.body = c.headers['cookie'] || '还没有设置cookie';
})








app.run(1234)